﻿function LoadMessages() {
    var template = $('#MessageListTemplate ul');

    $("#LoadingImage").show();
    $.getJSON("/Services/MessageService.svc/GetMessages",
                        function (d) {
                            $("#MessageList").html('');
                            $(template).bindTo(d.d, { appendTo: '#MessageList' });
                            syncBars();
                            $("#LoadingImage").hide();
                            $(".messageLink").removeClass("messageLinkActive");
                        });
}

function NewMessage() {
    $("#NewMessageDialog").dialog({ modal: true, resizable: false, width: 500, height: 250 });
}

function Delete(guid) {
    var url = $.format('/Services/MessageService.svc/DeleteMessage?messageGUID={0}',
                        guid)
    $.ajax({ url: url,
        success: function (d, status) {
            LoadMessages();
        }
    });
}

function SendMessage() {
    var msg = $("#HeadLoginView_txtMessage").val();
    var subject = $("#HeadLoginView_txtTitle").val();

    var url = $.format('/Services/MessageService.svc/SendMessage?message={"Title":"{0}","Message":"{1}"}',
                        subject, msg)
    $.ajax({ url: url,
        success: function (d, status) {
            $("#NewMessageDialog").dialog('close');
        }
    });
}


function AttachMessageMenu() {
    $(".messageLink").click(function () {
        LoadMessages();
        var menu = $("#MessageMenu");

        var left = $(".messageLink").offset().left;
        $(menu).css("left", left);


        if ($(menu).is(":hidden")) {
            $(menu).slideDown(500, function () {
                $(menu).focus();
                $(menu).focusout(function () {
                    $(this).slideUp(500);
                });
            });
        }
        else {
            $(menu).slideUp(500);
        }
        return false;
    });
}

function AttachMessageChecker() {
    var link = $('.messageLink');
    if ($(link).length == 1) {
        $(link).data("mails", -1);

        $(this).everyTime(5000, "mpmailcheck", function () {
            $.getJSON("/Services/MessageService.svc/GetMessageCount",
                        function (data) {
                            var newMails = data.d;
                            var oldMails = $(link).data("mails");

                            if (newMails > 0 && newMails > oldMails) {
                                $(link).addClass("messageLinkActive");
                            } else {

                            }
                            $(link).data("mails", newMails);
                        });
        });
    }
}